package org.richin.io.util;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;



/**
 * 这个类提供了一些根据类的class文件位置来定位的方法
 * 
 * @author Administrator
 * 
 */
public class PathUtil {
	/**
	 * 获取一个Class的绝对路径
	 * 
	 * @param clazz
	 * @return Class的绝对路径
	 */
	public static String getPathByClass(Class clazz) {
		String path = null;
		try {
			URI uri = clazz.getResource("").toURI();
			File file = new File(uri);
			path = file.getCanonicalPath();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return path;

	}

	/**
	 * 获取一个文件相对于一个Class相对的绝对路径
	 * 
	 * @param clazz
	 *            Class对象
	 * @param relativePath
	 *            Class对象的相对路径
	 * @return 文件绝对路径
	 */
	public static String getFilePathByClass(Class clazz, String relativePath) {
		String filePath = null;
		String clazzPath = getPathByClass(clazz);
		StringBuffer sbPath = new StringBuffer(clazzPath);
		sbPath.append(File.separator);
		sbPath.append(relativePath);
		File file = new File(sbPath.toString());
		try {
			filePath = file.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return filePath;

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(getPathByClass(PathUtil.class));
		System.out.println(getFilePathByClass(PathUtil.class,"../../images/logo.gif"));
     

	}

}
